package com.tandil.seo;

import android.content.*;
import android.widget.*;
import utils.Constantes;
import utils.PersistenceData;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.text.method.TextKeyListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends Activity {

	private Spinner spinCalles, spinPatente;
	private SeekBar alturaBar, horasBar;
	private TextView saldoDisponible, alturaTxt, horasTxt;
	private Button enviarBtn;
	public String codigo_Calle, patente;
	public Resources res;
	public int Altura = 300, horas = 1;
	public String[] patentes = {"", "", "", ""};
	public ArrayAdapter<CharSequence> patenteAdapter;
    public ImageButton botonMas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        res = getResources();
        bindViews();
    }
	
	@Override
	protected void onResume(){
	    super.onResume();
	    saldoDisponible.setText(PersistenceData.readSaldo(this, Constantes.ARCHIVO_SALDO));
	    ActualizarPatenteSpinner();
	}

    private void bindViews() {
    	//Patente Edit Text
    	spinPatente = (Spinner)findViewById(R.id.patentesSpinner);
    	ActualizarPatenteSpinner();

        botonMas = (ImageButton)findViewById(R.id.boton_Mas);
        botonMas.setOnClickListener(new botonMasOnClickListener());
        //botonMas.setOnLongClickListener(new botonMasOnLongClickListener());
    	
    	//Calles Spinner
		spinCalles = (Spinner)findViewById(R.id.Calle_Spinner);
		ArrayAdapter<CharSequence> callesAdapter = ArrayAdapter.createFromResource(this, R.array.calles, android.R.layout.simple_spinner_dropdown_item);
		patenteAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinCalles.setAdapter(callesAdapter);
		spinCalles.setOnItemSelectedListener(new CallesItemSelectedListener());
		
		//Altura SeekBar
		alturaBar = (SeekBar)findViewById(R.id.Altura_Bar);
		alturaBar.setOnSeekBarChangeListener(new AlturaBarChangeListener());
		//Altura Txt
		alturaTxt = (TextView)findViewById(R.id.Altura_Txt);
		
		//Horas SeekBar
		horasBar = (SeekBar)findViewById(R.id.Horas_Bar);
		horasBar.setOnSeekBarChangeListener(new HorasBarChangeListener());
		//Horas Txt
		horasTxt = (TextView)findViewById(R.id.Horas_Txt);
		
		//Saldo Disponible Text
		saldoDisponible = (TextView)findViewById(R.id.Saldo_Text);
		saldoDisponible.setText(PersistenceData.readSaldo(this, Constantes.ARCHIVO_SALDO));
		
		//Enviar SMS Button
		enviarBtn = (Button)findViewById(R.id.Enviar_btn);
		enviarBtn.setOnClickListener(new EnviarBtnListener());
	}
    
    
	public class botonMasOnLongClickListener implements OnLongClickListener {
		@Override
		public boolean onLongClick(View arg0) {
			Intent intentin = new Intent(MainActivity.this, Confirmation_Screen.class);
            intentin.putExtra("CONFIRMACION", "TRANSACCION");
            intentin.putExtra("DOMINIO", "Dominio");
            intentin.putExtra("INICIO", "Inicio");
            intentin.putExtra("FIN", "FIN");
            intentin.putExtra("SALDO", "3,40");
            intentin.putExtra("TRANSACCION", "ASDA");
            intentin.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intentin.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
            PersistenceData.writeHoras(MainActivity.this, String.valueOf(horas), Constantes.ARCHIVO_HORAS);
            MainActivity.this.startActivity(intentin);
			return false;
		}
	} 
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.settings:
	        	Intent intent = new Intent(MainActivity.this, Configuration.class);
	        	startActivity(intent);
	            return true;
	        case R.id.cargarCredito:
	        	DialogoIngresoTarjetaCargaCredito();
	        	return true;
	        case R.id.about:
	        	AlertDialog.Builder alert = new AlertDialog.Builder(this);
	    		alert.setTitle("Sistema Estacionamiento Tandil");
	    		alert.setMessage(Constantes.TEXTO_ABOUT);
	    		
	    		alert.setPositiveButton(R.string.valorar_app, new DialogInterface.OnClickListener() {
	    			public void onClick(DialogInterface dialog, int whichButton) {
	    				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.tandil.seo") ) );
	    				}
	    			});

	    		alert.setNegativeButton(R.string.cerrar, new DialogInterface.OnClickListener() {
	    			  public void onClick(DialogInterface dialog, int whichButton) {}
	    			});
	        	
	        	alert.show();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}

    private class botonMasOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Configuration.class);
            startActivity(intent);
        }
    }
	
	public void ActualizarPatenteSpinner(){
		patentes = PersistenceData.readPatentes(this, Constantes.ARCHIVO_PATENTES);
		patenteAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item);
		for (int i=0; i < patentes.length-1; i++){//Menos 1 ya que cuando hace Split agrega uno ultimo en null CREO
			if (!(patentes[i].isEmpty())){
				patenteAdapter.add(patentes[i]);
			}
		}
		spinPatente.setAdapter(patenteAdapter);
	}

	public class CallesItemSelectedListener implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			codigo_Calle = res.getStringArray(R.array.codigo_calles)[arg2];
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {}

	}
	
	public class AlturaBarChangeListener implements OnSeekBarChangeListener {
		@Override
		public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
			Altura = 300 + (arg1*100);
			alturaTxt.setText(String.valueOf(Altura));
		}
		@Override       
		public void onStartTrackingTouch(SeekBar arg0) {}
		@Override
		public void onStopTrackingTouch(SeekBar arg0) {}
	}
    
	public class HorasBarChangeListener implements OnSeekBarChangeListener {
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			horas = progress + 1;
			horasTxt.setText(String.valueOf(horas));					
		}
		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {}
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {}
	}

	public class EnviarBtnListener implements OnClickListener {
		@Override
		public void onClick(View arg0) {
			try{ 
				if ((!spinPatente.getSelectedItem().toString().isEmpty()) || (!codigo_Calle.isEmpty()) || (!String.valueOf(Altura).isEmpty()) ||
						(!String.valueOf(horas).isEmpty()) || (!String.valueOf(horas).isEmpty())){
					
					final String mensaje = spinPatente.getSelectedItem().toString() + " " + 
							codigo_Calle + " " + String.valueOf(Altura) + " " + String.valueOf(horas);
					
					AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
					alert.setTitle(R.string.se_enviara_el_mensaje);
					alert.setMessage(mensaje);
	
					alert.setPositiveButton(R.string.enviar, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						sendSMS(getString(R.string.smsPhoneNumber), mensaje);
                        PersistenceData.writeHoras(MainActivity.this, String.valueOf(horas), Constantes.ARCHIVO_HORAS);
					}
					});
	
					alert.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
					  public void onClick(DialogInterface dialog, int whichButton) {}
					});
	
					alert.show();								
				}else{
					Toast.makeText(MainActivity.this, R.string.por_favor_ingrese_todos_los_datos, Toast.LENGTH_SHORT).show();
				}
			}catch (NullPointerException e) { //Exeption because spinPatente could be empty
				Toast.makeText(MainActivity.this, R.string.por_favor_ingrese_todos_los_datos, Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	//---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
 
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
 
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
 
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), R.string.sms_enviado, 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));
 
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "Espere Respuesta del sistema de estacionamientos", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS no pudo ser recibido", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        
 
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
    }
	
	public void DialogoIngresoTarjetaCargaCredito(){
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle(R.string.cargar_credito);
		alert.setMessage(R.string.ingrese_numero_de_tarjeta_);

		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		input.setKeyListener(new TextKeyListener(TextKeyListener.Capitalize.CHARACTERS, true));
		alert.setView(input);
		
		alert.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
			String value = input.getText().toString();
			if (!value.isEmpty()){
				sendSMS(getString(R.string.smsPhoneNumber), value);
			}else {
				Toast.makeText(MainActivity.this, R.string.ingrese_una_tarjeta_valida, Toast.LENGTH_SHORT).show();
			}
		}
		});

		alert.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
		  public void onClick(DialogInterface dialog, int whichButton) {}
		});

		alert.show();
	}

}
	

	
   
